<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-select
              v-model="handleChecked"
              style="width:110px;marginRight:5px;"
              clearable
              placeholder="请选择"
              @change="getInitData"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-input
              v-model="searchInfo.keyword"
              placeholder="岗位/角色/人员"
              style="width:132px;marginRight:5px;"
              clearable
            />
            <el-button type="primary" @click="handleSearchUser">搜 索</el-button>
          </div>
          <div class="userScroll" style="height:500px;overflow:auto">
            <el-tree
              v-if="orTree"
              :data="data"
              default-expand-all
              :props="defaultProps"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            />
            <div v-else>
              <li
                v-for="item in notOrg"
                :key="item.id"
                :class="item.id===selectUserId?'selectUser userInfo':'userInfo'"
                style="cursor:pointer;"
                @click="handleNodeClick(item)"
              >{{ isRole ? item.roleName : item.userName }}</li>
              <div style="margin-top:15px;" class="clearfix">
                <Pagination
                  class="right"
                  :total-count="totalCount"
                  :page-size="searchInfo.page.pageSize"
                  :current-page="searchInfo.page.pageNo"
                  @handleSizeChange="handleSizeChange"
                  @handleCurrentChange="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <h2 class="left">权限设置</h2>
            <el-button class="right" type="primary" :disabled="!isDisabled" @click="saveInfo">保 存</el-button>
          </div>
          <div class="userScroll" style="height:500px;overflow:auto">
            <el-tree
              ref="tree"
              :data="permission"
              show-checkbox
              default-expand-all
              node-key="id"
              :expand-on-click-node="false"
              highlight-current
              :props="defaultProps1"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
let arrList = [];
function reduceArr1(arr) {
  arr.forEach(v => {
    if (v.children) {
      reduceArr1(v.children);
    } else {
      arrList.push(v.id);
    }
  });
}
import { reduceArr, createDics } from "~/utils/util";
import mmUrl from "~/utils/utilUrl";
import Pagination from "~/components/commom/pagination";
export default {
  components: {
    Pagination
  },
  data() {
    return {
      totalCount: 0,
      accreditChildren: {},
      accreditArr: [],
      handleSelectCategory: "",
      orTree: true, // 左边树
      data: [], // 组织树数组
      handleTreeChecked: {}, // 左边树选中
      handleChecked: "org", // 下拉框
      notOrg: [],
      isRole: true,
      selectUserId: "",
      totalCount: 0,
      searchInfo: {
        keyword: "",
        page: {
          maxResultCount: 0,
          pageNo: 0,
          pageSize: 10,
          skipCount: 0
        }
      }, // 输入框
      defaultProps: {
        children: "children",
        label: "orgName"
      },
      defaultProps1: {
        children: "children",
        label: "permissionName"
      },
      permission: [], // 权限树数组
      options: [
        {
          label: "组织",
          value: "org"
        },
        {
          label: "角色",
          value: "role"
        },
        {
          label: "用户",
          value: "user"
        }
      ]
    };
  },
  computed: {
    isDisabled() {
      if (!this.accreditChildren.saveAuth) {
        return false;
      } else {
        if (!this.selectUserId) {
          return false;
        } else {
          return true;
        }
      }
    }
  },
  mounted() {
    this.getInitTreeData();
    const result = JSON.parse(sessionStorage.getItem("menu"));
    this.accreditArr = reduceArr(result, "/" + this.$route.name);
    this.accreditChildren = createDics(
      this.accreditArr.children,
      "permissionCode"
    );
  },
  methods: {
    handleSizeChange(val) {
      this.searchInfo.page.pageSize = val;
      this.handleSearchUser();
    },
    handleCurrentChange(val) {
      this.searchInfo.page.pageNo = val;
      this.handleSearchUser();
    },
    sureHandleSelect() {
      return new Promise(resolve => {
        if (!this.handleSelect.id) {
          this.$message.error("请先选择");
        } else {
          resolve();
        }
      });
    },
    saveInfo() {
      if (!this.selectUserId) {
        return false;
      }
      const that = this;
      const result = this.$refs.tree.getCheckedNodes(false, true).map(v => ({
        dataId: that.handleTreeChecked.id,
        permissionId: v.id,
        type: that.handleChecked
      }));
      this.$post({
        url: mmUrl.permissionRelation.create,
        data: {
          dataId: that.handleTreeChecked.id,
          items: result
        }
      }).then(res => {
        this.$message({
          type: "success",
          message: "操作成功"
        });
        this.handleTreeChecked = {};
      });
    },
    handleNodeClick(res) {
      this.selectUserId = res.id;
      reduceArr1(this.permission);
      this.handleTreeChecked = res;
      this.$post({
        url: mmUrl.permissionRelation.getPer,
        data: {
          dataId: res.id
        }
      }).then(res => {
        if (res.permissionRelations) {
          const result = res.permissionRelations.map(v => v.permissionId);
          const result1 = [];
          arrList.map(v => {
            result.map((vv, index) => {
              if (v === vv) {
                result1.push(vv);
              }
            });
          });
          this.$refs.tree.setCheckedKeys(result1);
        }
      });
    },
    getInitData(res) {
      arrList = [];
      this.$refs.tree.setCheckedKeys(arrList);
      this.handleSelectCategory = res;
      if (res !== "org") {
        this.orTree = false;
      } else if (res === "org") {
        this.orTree = true;
      }
      this.$post({
        url:
          res === "org"
            ? mmUrl.permissionRelation.getOrgs
            : res === "role"
            ? mmUrl.permissionRelation.getRoles
            : mmUrl.permissionRelation.getUsers,
        data:
          res === "org"
            ? {}
            : res === "role"
            ? {
                keyword: "",
                page: {
                  maxResultCount: 0,
                  pageNo: 0,
                  pageSize: 20,
                  skipCount: 0
                }
              }
            : {
                keyword: "",
                page: {
                  maxResultCount: 0,
                  pageNo: 0,
                  pageSize: 20,
                  skipCount: 0
                }
              }
      }).then(rest => {
        this.selectUserId = "";
        if (res === "org") {
          this.data = rest;
        } else if (res === "role") {
          this.isRole = true;
          this.notOrg = rest.items.items;
          this.totalCount = rest.items.totalCount;
        } else if (res === "user") {
          this.isRole = false;
          this.notOrg = rest.items.items;
          this.totalCount = rest.items.totalCount;
        }
      });
    },
    handleSearchUser() {
      this.$post({
        url:
          this.handleSelectCategory === "org"
            ? mmUrl.permissionRelation.getOrgs
            : this.handleSelectCategory === "role"
            ? mmUrl.permissionRelation.getRoles
            : mmUrl.permissionRelation.getUsers,
        data: this.searchInfo
      }).then(res => {
        this.notOrg = res.items.items;
      });
    },
    getInitTreeData() {
      this.$post({
        url: mmUrl.permissionRelation.pageLoad,
        data: {
          parentId: ""
        }
      }).then(res => {
        this.data = res.orgs;
        this.permission = JSON.parse(JSON.stringify(res.permission));
      });
    }
  }
};
</script>

<style>
.userInfo {
  line-height: 40px;
  text-indent: 15px;
  border-bottom: 1px solid #eee;
}
.selectUser {
  background: #eee;
}
</style>
